<?php
class App_Module_Front_Router_Http extends Mozg_Router_Router
{

	public function DetectCtrlAndAction(array $elements = array())
	{
		$ctrlName = $actionName = '';

		if (isset($elements['itemId']))
		{
			$stElement = Mozg_Mapper::Get('Structure')->GetOne(array('id' => $elements['itemId']));
			if ($stElement)
			{
				$pageType = $stElement->GetPageType();
				$pageTypes = Mozg_Cfg::Get('global/structure')->GetPageTypes();
				
				if (isset($pageTypes[$pageType]))
				{
					$ctrlName = $pageTypes[$pageType]['module'];
					$actionName = isset($elements['action']) ? $elements['action'] : '';
				}
			}
		}
		
		return array($ctrlName, $actionName);
	}

	/**
	 * определяем поведение controller & action
	 *
	 */
	public function Build(array &$elements = array())
	{
		$url = array();
		
		if (isset($elements['itemId']))
		{
			$stElement = Mozg_Mapper::Get('Structure')->GetOne(array('id' => $elements['itemId']));
			if ($stElement) $url = array($stElement->GetFullUrl());
			unset($elements['itemId']);
		}

		return $url;
	}
	
	public function Parse(array &$segments = array())
	{
		$elements = array();

		$fullUrl = '';
        $pathElementIds = array();
        do {
            $isInStruct = false;
            $url = $segments[0];
            if (strlen($url)) {
                $fullUrl .= $url . '/';
                $stElement = Mozg_Mapper::Get('Structure')->GetOne(array('url' => $fullUrl, 'active' => true));
                if ($stElement) {
                    $pathElementIds[] = $stElement->GetId();
                    $isInStruct = true;
                    array_shift($segments);
                }
            }
        } while ($isInStruct);
        
        if (!sizeof($pathElementIds))
        {
        	$rootElement = Mozg_Mapper::Get('Structure')->GetOne(array('url' => '', 'active' => true));
        	if ($rootElement) $pathElementIds[] = $rootElement->GetId();
        }

        $elements['itemId'] = $pathElementIds[sizeof($pathElementIds) - 1];
		return $elements;
	}

	/* ------------ роутеры контроллеров -----------------*/
	public function BuildStructure(array &$elements = array())
	{
		return array();
	}

	public function ParseStructure(array &$segments = array())
	{
		return array();
	}
}